package com.agricultural.machine.command;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 任务管理器类 - 命令模式的调用者
 */
public class TaskManager {
    private static TaskManager instance;
    private final List<TaskCommand> activeCommands;
    private final Stack<TaskCommand> commandHistory;
    
    private TaskManager() {
        this.activeCommands = new ArrayList<>();
        this.commandHistory = new Stack<>();
    }
    
    public static synchronized TaskManager getInstance() {
        if (instance == null) {
            instance = new TaskManager();
        }
        return instance;
    }
    
    /**
     * 执行命令
     */
    public void executeCommand(TaskCommand command) {
        activeCommands.add(command);
        command.execute();
        commandHistory.push(command);
        
        System.out.println("任务执行成功: " + command.getDescription());
    }
    
    /**
     * 撤销最后一个命令
     */
    public void undoLastCommand() {
        if (!commandHistory.isEmpty()) {
            TaskCommand command = commandHistory.pop();
            command.undo();
            activeCommands.remove(command);
            
            System.out.println("撤销任务: " + command.getDescription());
        } else {
            System.out.println("没有可撤销的任务");
        }
    }
    
    /**
     * 获取活动命令列表
     */
    public List<TaskCommand> getActiveCommands() {
        return new ArrayList<>(activeCommands);
    }
    
    /**
     * 获取命令历史
     */
    public Stack<TaskCommand> getCommandHistory() {
        return (Stack<TaskCommand>) commandHistory.clone();
    }
    
    /**
     * 清除所有命令
     */
    public void clearCommands() {
        for (TaskCommand command : new ArrayList<>(activeCommands)) {
            command.undo();
        }
        activeCommands.clear();
        commandHistory.clear();
        
        System.out.println("所有任务已清除");
    }
} 